/*
 * 集中 xcodebuild 的功能
 */
const loading = require('ora')()
const shell = require('shelljs')
const print = require('./print')

/*
 * @arguments：build 参数，参数如下
 * - target: project 或 workspace
 * - targetValue: xxx.xcodepro 或 xxx.xcworkspace
 * - scheme: 去除后缀的 targetValue
 * - configuration: Debug 或 Release
 * - sdk: iphonesimulator 或 iphoneos
 * - buildDir: 可选，编译产物存放位置
 * 
 * @resolve 返回成功日志
 * @reject 返回失败日志
 */
exports.buildCommand = function(arguments) {
    return new Promise((resolve, reject) => {
        let build_cmd = 'xcodebuild build ' +
                                    `-${arguments.target} ${arguments.targetValue} ` +
                                    `-scheme ${arguments.scheme} ` +
                                    `-configuration ${arguments.configuration} ` +
                                    `-sdk ${arguments.sdk} ` +
                                    'ONLY_ACTIVE_ARCH=NO'
        if (arguments.buildDir) {
            build_cmd = build_cmd + ` BUILD_DIR=${arguments.buildDir}`
        }
        console.log(build_cmd)
        let build_startTime = new Date().getTime()
        loading.start('building...')
        shell.exec(build_cmd, {silent:true}, function(code, stdout, stderr) {
            loading.stop()
            // 成功 code=0
            if (code != 0) {
                reject(stderr)
                return
            }
            let build_endTime = new Date().getTime()
            print.successLog(`** BUILD SUCCEEDED ** [${(build_endTime - build_startTime)/1000} sec]`)
            resolve(stdout) 
        })
    })
}